package io.github.wanggit.antrpc.console.zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class DefaultZkNodeOperator implements IZkNodeOperator {

    @Autowired private IZkClient zkClient;

    @Override
    public void deleteNode(String fullPath) {
        try {
            zkClient.getCuratorFramework().delete().deletingChildrenIfNeeded().forPath(fullPath);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("delete " + fullPath + " error. ", e.getMessage());
            }
            throw new RuntimeException(e);
        }
    }

    @Override
    public void setNodeData(String fullPath, byte[] data) {
        try {
            zkClient.getCuratorFramework().setData().forPath(fullPath, data);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("set node data " + fullPath + " error.", e);
            }
        }
    }

    @Override
    public byte[] getNodeData(String fullPath) {
        try {
            return zkClient.getCuratorFramework().getData().forPath(fullPath);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("get data from " + fullPath + " error." + e.getMessage());
            }
        }
        return null;
    }

    @Override
    public boolean existsNode(String fullPath) {
        try {
            Stat stat = zkClient.getCuratorFramework().checkExists().forPath(fullPath);
            return null != stat;
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("check node " + fullPath + " exists error.");
            }
        }
        return false;
    }

    @Override
    public void createNode(String fullPath, byte[] data) {
        try {
            zkClient.getCuratorFramework()
                    .create()
                    .creatingParentsIfNeeded()
                    .forPath(fullPath, data);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("create node " + fullPath + " error." + e.getMessage());
            }
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getChildren(String fullPath) {
        try {
            return zkClient.getCuratorFramework().getChildren().forPath(fullPath);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("get children node " + fullPath + " error." + e.getMessage());
            }
            throw new RuntimeException(e);
        }
    }
}
